/**
 * description
 * <p>fill description</p>
 * @author zido
 * @since 2017/6/4 0004
 */

import React from 'react'
import {Form,Modal,Input,Tabs,Icon, Button,Card,Select,Spin} from 'antd'
import PropTypes from 'prop-types'
import './BusinessAdd.less'
import {isEmpty,post,checkBankNum,patterns} from '../../Util'
const FormItem = Form.Item
const TabPane = Tabs.TabPane
const SelectOption = Select.Option
let uuid = 0
let bankUuid = 0
class BusinessForm extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      shopKeys : [{k:0}],
      banKeys : [{k:0}],
      activeTab: 0,
      disabled:false,
      fetching:false,
      value:null,
      introducesData:[],
    }
  }

  componentWillMount(){
    const {bankCards,shops,user,businessUser} = this.props.data
    this.setState({
      shopKeys : isEmpty(shops)?[{k:0}]:shops.map((value,index)=>({id:value.id,k:index})),
      banKeys : isEmpty(bankCards)?[{k:0}]:bankCards.map((value,index)=>({id:value.id,k:index})),
      activeTab: 0,
      disabled:!isEmpty(this.props.data),
      userId:isEmpty(user)?null:user.id,
      businessUserId:isEmpty(businessUser)?null:user.id,
    })
  }
  handleAddShop(){
    uuid++
    const {shopKeys} = this.state
    const nextKeys = shopKeys.concat({k:uuid})
    this.setState({
      shopKeys:nextKeys,
    })
  }

  handleTabChange(tab){
    if(tab < 0)
      tab = 2
    if(tab > 2)
      tab = 0
    this.setState({
      activeTab:tab,
    })
  }

  handleRemoveShop(k){
    const {disabled} = this.state
    if(disabled)
      return
    const {shopKeys} = this.state
    if(shopKeys.length === 1)
      return
    this.setState({
      shopKeys:shopKeys.filter(current=>current.k !== k),
    })
  }
  handleAddBank(){
    bankUuid++
    const {banKeys} = this.state
    const nextKeys = banKeys.concat({k:bankUuid})
    this.setState({
      banKeys:nextKeys,
    })
  }
  handleRemoveBank(k){
    const {disabled} = this.state
    if(disabled)
      return
    const {banKeys} = this.state
    if(banKeys.length === 1)
      return
    this.setState({
      banKeys:banKeys.filter(current=>current.k !== k),
    })
  }
  handleEdited(){
    this.setState({
      disabled:!this.state.disabled
    })
  }
  componentDidMount(){
    const {insertForm,data,form} = this.props
    const {shopKeys, banKeys} = this.state
    const {businessUser,user} = data
    insertForm(form,isEmpty(user)?null:user.id,isEmpty(businessUser)?null:businessUser.id,shopKeys,banKeys)
  }

  fetchUsers(value){
    this.setState({
      fetching:true,
      value:value,
      introducesData:[],
    })
    post('/api/center/business/introduce/list?key='+value).then(json => {
      this.setState({
        fetching:false,
        introducesData:json.data,
      })
    })
  }
  handleUsersChange(value){
    this.setState({
      value,
      data: [],
      fetching: false,
    })
  }
  /**
   * 查看是否传入数据，如果有传入，
   * 则需要将数据加载进框内，显示编辑按钮，点击即可编辑
   */
  render (){
    const {onCancel,onOk,form,visible,width,confirmLoading,data} = this.props
    const {businessUser,bankCards,shops,user} = data
    const { getFieldDecorator} = form
    const {disabled,bankName} = this.state
    const itemLayout = {
      labelCol: {
        span:6
      },
      wrapperCol: {
        span:18
      },
    }
    const {shopKeys, banKeys} = this.state
    const shopForms = shopKeys.map(({k}, index)=>(
        <Card key={'item'+k} title={'店铺'+(index + 1)} bordered={false} style={{margin:'5px 0'}} extra={<Icon type="delete" className="close-icon-btn" onClick={this.handleRemoveShop.bind(this,k)} disabled={shopKeys.length === 1 || disabled}/>}>
          <Form>
            <FormItem key={k+'shopName'} label={'店铺名称'} hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('shops['+k+'].shopName', {
                initialValue:(isEmpty(shops) || isEmpty(shops[k]))?'':shops[k].shopName,
                rules: [{ required: true, message: '请输入店铺名称' }],
              })(<Input disabled = {disabled}/>)}
            </FormItem>
            <FormItem key={k+'shopType'} label={'店铺类型'} hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('shops['+k+'].shopType',{
                initialValue:(isEmpty(shops) || isEmpty(shops[k]))?'':shops[k].shopType,
                rules: [{ required: true, message: '请输入店铺类型' }],
              })(<Input disabled = {disabled}/>)}
            </FormItem>
            <FormItem key={k+'shopUrl'} label={'店铺链接'} hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('shops['+k+'].shopUrl', {
                initialValue:(isEmpty(shops) || isEmpty(shops[k]))?'':shops[k].shopUrl,
                rules: [{ required: true, message: '请输入店铺链接' }],
              })(<Input disabled = {disabled}/>)}
            </FormItem>
            <FormItem key={k+'platformId'} label={'平台'} {...itemLayout}>
              {getFieldDecorator('shops['+k+'].platformId',{
                initialValue:(isEmpty(shops) || isEmpty(shops[k]))?'0':shops[k].platformId+'',
                rules: [{ required: true, message: '请选择' }],
              })(
                <Select style={{ width: 120 }} disabled = {disabled}>
                  <SelectOption value="0">淘宝</SelectOption>
                  <SelectOption value="1" disabled>天猫</SelectOption>
                  <SelectOption value="2" disabled>京东</SelectOption>
                </Select>)}
            </FormItem>
          </Form>
        </Card>
      ))
    const bankForms = banKeys.map(({k},index) => (
      <Card key={'item'+k} title={'银行卡'+(index + 1)} bordered={false} style={{margin:'5px 0'}} extra={<Icon type="delete" className="close-icon-btn" onClick={this.handleRemoveBank.bind(this,k)} disabled={banKeys.length === 1 || disabled}/>}>
        <Form>
          <FormItem key={k+'shopName'} label={'银行卡号'} {...itemLayout} hasFeedback={!disabled || isEmpty(data)}>
            {getFieldDecorator('bankCards['+k+'].bankCardNumber', {
              initialValue:isEmpty(bankCards) || isEmpty(bankCards[k])?'':bankCards[k].bankCardNumber,
              rules: [{
                required: true, message: '请输入银行卡号'
              },{
                validator:(rule, value, callback)=>{
                  if(!checkBankNum(value)){
                    callback('请输入正确的银行卡号')
                    this.setState({
                      bankName:'',
                    })
                  }else
                    post('/api/center/business/bankCardCheck?cardNumber='+value).then((json)=>{
                      this.setState({
                        bankName:json.data,
                      })
                      callback()
                    })
                }
              }],
            })(<Input disabled = {disabled}/>)}
          </FormItem>
          <FormItem key={k+'shopType'} label={'开户行（自动生成）'} {...itemLayout} hasFeedback={!disabled || isEmpty(data)}>
            {getFieldDecorator('bankCards['+k+'].bankName', {
              initialValue:isEmpty(bankName)?(isEmpty(bankCards) || isEmpty(bankCards[k])?'':bankCards[k].bankName):bankName,
              rules: [{ required: true, message: '请输入开户行' }],
            })(<Input disabled = {disabled}/>)}
          </FormItem>
          <FormItem key={k+'phoneNumber'} label={'银行绑定手机号'} {...itemLayout} hasFeedback={!disabled || isEmpty(data)}>
            {getFieldDecorator('bankCards['+k+'].phoneNumber', {
              initialValue:isEmpty(bankCards) || isEmpty(bankCards[k])?'':bankCards[k].phoneNumber,
              rules: [{
                required: true, message: '请输入银行绑定手机号'
              },{
                pattern:patterns.phoneNumber,
                message:'请输入正确的手机号'
              }],
            })(<Input disabled = {disabled}/>)}
          </FormItem>
          <FormItem key={k+'bindName'} label={'银行卡绑定人姓名'} {...itemLayout} hasFeedback={!disabled || isEmpty(data)}>
            {getFieldDecorator('bankCards['+k+'].bindName', {
              initialValue:isEmpty(bankCards) || isEmpty(bankCards[k])?'':bankCards[k].bindName,
              rules: [{ required: true, message: '请输入银行绑定人姓名' }],
            })(<Input disabled = {disabled}/>)}
          </FormItem>
          <FormItem key={k+'bindCard'} label={'银行卡身份证号'} {...itemLayout} hasFeedback={!disabled || isEmpty(data)}>
            {getFieldDecorator('bankCards['+k+'].bindCard', {
              initialValue:isEmpty(bankCards) || isEmpty(bankCards[k])?'':bankCards[k].bindCard,
              rules: [{
                required: true, message: '请输入银行绑定人身份证号'
              },{
                pattern:patterns.idCard,message:'请输入正确的身份证号',
              }],
            })(<Input disabled = {disabled}/>)}
          </FormItem>
        </Form>
      </Card>
    ))


    const {introducesData,fetching,value,activeTab} = this.state
    return <Modal
      title="商家管理"
      visible={visible}
      maskClosable={false}
      width={width}
      okText="提交"
      onCancel={onCancel}
      footer={(
          <div>
            {activeTab !== 0?<Button className="pull-left" onClick={this.handleTabChange.bind(this,activeTab - 1)} size="large">上一步</Button>:null}
            <Button onClick={onCancel} size="large">取消</Button>
            {activeTab !== 2?<Button onClick={this.handleTabChange.bind(this,activeTab + 1)} size="large">下一步</Button>:<Button onClick={onOk} loading={confirmLoading} type="primary" size="large">确定</Button>}
          </div>
      )}
    >
      <Tabs activeKey={activeTab+''}
            tabBarExtraContent={isEmpty(this.props.data)?null:<Icon type="edit" className="close-icon-btn" onClick={this.handleEdited.bind(this)}/>}
            onTabClick={(e)=>this.setState({activeTab:parseInt(e)})}
      >
        <TabPane tab="基本信息" key={'0'}>
          {isEmpty(user)?null:(<Form>
            <FormItem label="登录用户账号：" key="username" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('user.username', {
                rules: [{ required: !isEmpty(user.username), message: '请输入用户名' }],
                initialValue:isEmpty(user)?'':user.username,
              })(
                <Input  disabled = {disabled}/>
              )}
            </FormItem>
            <FormItem label="用户登录密码：" key="password" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('user.password', {
                rules: [{ required: !isEmpty(user.password), message: '请输入登录密码' }],
                initialValue:isEmpty(user)?'':user.password,
              })(
                <Input  disabled = {disabled}/>
              )}
            </FormItem>
            <FormItem label="用户状态：" key="enabled" {...itemLayout}>
              {getFieldDecorator('user.enabled', {
                rules: [{ required: true, message: '填写用户状态' }],
                initialValue:isEmpty(user)?'':user.enabled+'',
              })(
                <Select disabled = {disabled}>
                  <SelectOption value="1">可用</SelectOption>
                  <SelectOption value="0">禁用</SelectOption>
                </Select>
              )}
            </FormItem>
            <FormItem label="用户最后登录ip地址：" key="ip" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('user.ip', {
                rules: [{ required: true, message: '填写用户最后登录ip地址' }],
                initialValue:isEmpty(user)?'':user.ip,
              })(
                <Input  disabled = {disabled}/>
              )}
            </FormItem>
          </Form>)}
          <Form>
            <FormItem label="商家名称：" key="nickname" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('businessUser.nickname', {
                rules: [{ required: true, message: '请输入商家名' }],
                initialValue:isEmpty(businessUser)?'':businessUser.nickname,
              })(
                <Input  disabled = {disabled}/>
              )}
            </FormItem>
            <FormItem label="联系手机号：" key="phoneNumber" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('businessUser.phoneNumber',{
                initialValue:isEmpty(businessUser)?'':businessUser.phoneNumber,
                rules:[{
                  required:true,message:'请输入联系电话'
                },{
                  pattern:patterns.phoneNumber,message:'请输入正确的手机号码'
                }]
              })(<Input disabled = {disabled}/>)}
            </FormItem>
            <FormItem label="联系人姓名：" key="contactName" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('businessUser.contactName',{
                initialValue:isEmpty(businessUser)?'':businessUser.contactName,
                rules:[{
                  required:true,message:'请输入联系人姓名'
                }]
              })(<Input disabled = {disabled}/>)}
            </FormItem>
            <FormItem label="常用联系微信："  key="wechat" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('businessUser.wechat',{
                initialValue:isEmpty(businessUser)?'':businessUser.wechat,
              })(<Input disabled = {disabled}/>)}
            </FormItem>
            <FormItem label="常用联系qq："  key="qq" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('businessUser.qq',{
                initialValue:isEmpty(businessUser)?'':businessUser.qq,
              })(<Input disabled = {disabled}/>)}
            </FormItem>
            <FormItem label="介绍人："  key="introduceName" hasFeedback={!disabled || isEmpty(data)} {...itemLayout}>
              {getFieldDecorator('businessUser.introduceName',{
                initialValue:isEmpty(businessUser)?((isEmpty(value))?'':value):((isEmpty(businessUser.introduceName) && disabled)?'未记录':businessUser.introduceName),
                rules:[{
                  required:true,message:'请填写介绍人'
                }]
              })(<Select
                mode="combobox"
                disabled = {disabled}
                placeholder="介绍人/序列号"
                filterOption={false}
                onSearch={this.fetchUsers.bind(this)}
                onChange={this.handleUsersChange.bind(this)}
                notFoundContent={fetching ? <Spin size="small" /> : null}
              >
                  {introducesData.map((d,index) => <SelectOption key={index} value={d.nickname}>{d.nickname}</SelectOption>)}
              </Select>)}
            </FormItem>
          </Form>
        </TabPane>
        <TabPane tab="店铺信息" key={'1'}>
          <div style={{padding:5}}>
            {shopForms}
          </div>
          <div style={{margin:'15px 0 0',textAlign:'center'}}>
            <Button size="small" type="dashed" onClick={this.handleAddShop.bind(this)} style={{ width: '200px' }} disabled={disabled}>
              <Icon type="plus" /> 添加店铺
            </Button>
          </div>
        </TabPane>
        <TabPane tab="银行卡信息" key={'2'}>
          <div style={{padding:5}}>
            {bankForms}
          </div>
          <div style={{margin:'15px 0 0',textAlign:'center'}}>
            <Button size="small" type="dashed" onClick={this.handleAddBank.bind(this)} style={{ width: '200px' }} disabled={disabled}>
              <Icon type="plus" /> 添加银行卡
            </Button>
          </div>

        </TabPane>
      </Tabs>
    </Modal>
  }
}
BusinessForm.propTypes = {
  onCancel:PropTypes.func.isRequired,
  onOk:PropTypes.func.isRequired,
  form:PropTypes.any.isRequired,
  visible:PropTypes.bool.isRequired,
  width:PropTypes.number,
  insertForm:PropTypes.func.isRequired,
  confirmLoading:PropTypes.bool,
  data:PropTypes.object,
}

BusinessForm.defaultProps = {
  width:700,
  visible:false,
  data:{},
}
const Com = Form.create()(BusinessForm)

Com.propTypes = {
  onCancel:PropTypes.func.isRequired,
  onOk:PropTypes.func.isRequired,
  visible:PropTypes.bool.isRequired,
  width:PropTypes.number,
  insertForm:PropTypes.func.isRequired,
  confirmLoading:PropTypes.bool,
  data:PropTypes.object,
}

export default Com